/**
 * This file is part of iSecurePasswords.
 *
 * iSecurePasswords is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * iSecurePasswords is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * iSecurePasswords. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Matthew MacGregor Created: 2012 iSecurePasswords, copyright 2013
 * Sudolink, LLC
 *
 */
package com.sudolink.isp.tasks;

import com.sudolink.isp.app.Application;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author matsu
 */
public class BackupTask implements Runnable {

    @Override
    public void run() {
        try {
            String dataDir = Application.getPathToAppDataDirectory();
            String src = Application.getPathToDatabase();
            String backupDir = "backups";
            int numberBackupsRetained = Application.getNumberBackupsRetained();
            long time = System.currentTimeMillis();
            File directory = new File(dataDir, backupDir);
            File[] files = directory.listFiles();

            if (files != null && files.length > numberBackupsRetained) {
                files = sortFilesByDate(files);
                File newestFile = files[files.length - 1];
                File srcFile = new File(src);
                if (verifyFilesAreIdentical(srcFile, newestFile)) {
                    return;
                }
            }
            if( files != null && files.length > 0 ) {
                File oldestFile = files[0];
                oldestFile.delete();
            }
            Files.createDirectories(Paths.get(dataDir, backupDir));
            Files.copy(Paths.get(src), Paths.get(dataDir, backupDir, "Database." + time + ".dbx"));

        } catch (IOException e) {
            Logger.getLogger(BackupTask.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    private boolean verifyFilesAreIdentical(File f1, File f2) throws FileNotFoundException, IOException {
        FileInputStream fis1 = new FileInputStream(f1);
        FileInputStream fis2 = new FileInputStream(f2);
        String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis1);
        String md52 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis2);
        if (md5.equals(md52)) {
            return true;
        } else {
            return false;
        }
    }

    private File[] sortFilesByDate(File[] files) {
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
            }
        });
        return files;
    }
}
